<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>畅销商品排行</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <style>
    body {
      font-family: 'Roboto', sans-serif;
      background-color: #f5f5f5;
      margin: 0;
      padding: 0;
    }
    .container {
      padding: 20px;
    }
    canvas {
      /* 适当减小宽度和高度 */
      max-width: 600px;
      max-height: 300px;
      margin: 20px auto;
    }
  </style>
</head>
<body>
<div class="container">
  <h1>畅销商品排行</h1>
  <canvas id="bestSellerChart"></canvas>
  <ul id="rankList"></ul>
</div>

<script>
  document.addEventListener('DOMContentLoaded', function () {
    fetch('/api/orderdetails/stats/product-quantity')
            .then(response => {
              if (!response.ok) {
                throw new Error('Network response was not ok');
              }
              return response.json();
            })
            .then(data => {
              // 将数据按销售数量降序排序，并取前5个商品
              const sortedData = Object.entries(data)
                      .sort((a, b) => b[1] - a[1])
                      .slice(0, 5);

              // 更新图表
              const ctx = document.getElementById('bestSellerChart').getContext('2d');
              const bestSellerChart = new Chart(ctx, {
                type: 'bar',
                data: {
                  labels: sortedData.map(item => item[0]), // 商品名称作为标签
                  datasets: [{
                    label: '销售数量',
                    data: sortedData.map(item => item[1]), // 商品销售数量
                    // 简化背景颜色
                    backgroundColor: 'rgba(0, 123, 255, 0.5)',
                    // 简化边框颜色和宽度
                    borderColor: 'rgba(0, 123, 255, 1)',
                    borderWidth: 0.5
                  }]
                },
                options: {
                  responsive: true,
                  maintainAspectRatio: false,
                  scales: {
                    y: {
                      beginAtZero: true
                    }
                  }
                }
              });

              // 更新文字排行
              const rankList = document.getElementById('rankList');
              rankList.innerHTML = sortedData.map((item, index) => `
                        <li>${index + 1}. ${item[0]} - ${item[1]} 件</li>
                    `).join('');
            })
            .catch(error => {
              console.error('Error fetching product quantity stats:', error);
              alert('加载畅销商品数据失败');
            });
  });
</script>
</body>
</html>